package api

import (
	"github.com/gin-gonic/gin"
	"go-caipu/pkg/api/helper"
	"go-caipu/pkg/constant"
	"go-caipu/pkg/services/schedule"
	"go-caipu/pkg/util"
)

func (hs *HTTPServer) GetSysJobPage(c *gin.Context) {
	cmd := schedule.GetSysJobPageCommand{}
	if err := helper.BindAndValidate(c, &cmd); err != nil {
		return
	}
	result, count, err := hs.scheduleService.GetSysJobPage(c.Request.Context(), cmd)
	if err != nil {
		helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
		return
	}
	helper.SuccessWithData(c, helper.Page{CurrentPage: cmd.PageIndex, PageSize: cmd.PageSize, List: result, Total: count})
}
func (hs *HTTPServer) GetSysJob(c *gin.Context) {
	cmd := schedule.GetSysJobCommand{}
	if err := helper.BindAndValidate(c, &cmd); err != nil {
		return
	}
	result, err := hs.scheduleService.Get(c.Request.Context(), cmd)
	if err != nil {
		helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
		return
	}
	helper.SuccessWithData(c, result)

}
func (hs *HTTPServer) CreateSysJob(c *gin.Context) {
	cmd := schedule.SysJob{}
	if err := helper.BindAndValidate(c, &cmd); err != nil {
		return
	}
	err := hs.scheduleService.Insert(c.Request.Context(), cmd)
	if err != nil {
		helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
		return
	}
	helper.SuccessWithOutData(c)
}

func (hs *HTTPServer) UpdateSysJob(c *gin.Context) {
	cmd := schedule.SysJob{}
	if err := helper.BindAndValidate(c, &cmd); err != nil {
		return
	}
	err := hs.scheduleService.Update(c.Request.Context(), cmd)
	if err != nil {
		helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
		return
	}
	helper.SuccessWithOutData(c)
}

func (hs *HTTPServer) RemoveSysJob(c *gin.Context) {
	cmd := schedule.RemoveSysJobCommand{}
	id := util.StringToInt(c.Param("id"))
	if id > 0 {
		cmd.Ids = []int{id}
	}
	err := hs.scheduleService.Remove(c.Request.Context(), cmd)
	if err != nil {
		helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
		return
	}
	helper.SuccessWithOutData(c)
}
func (hs *HTTPServer) GetSysJobLogPage(c *gin.Context) {
	cmd := schedule.GetSysJobLogPageCmd{}
	if err := helper.BindAndValidate(c, &cmd); err != nil {
		return
	}
	if len(cmd.DateTimeRange) == 2 {
		cmd.BeginTime = cmd.DateTimeRange[0]
		cmd.EndTime = cmd.DateTimeRange[1]
	}
	result, count, err := hs.scheduleService.GetJobLogPage(c.Request.Context(), cmd)
	if err != nil {
		helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
		return
	}
	helper.SuccessWithData(c, helper.Page{CurrentPage: cmd.PageIndex, PageSize: cmd.PageSize, List: result, Total: count})
}
